package com.example.linktop.localbroadcastdemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    static final String NOTINAME = "LocalBroadCast"; //通知名称

    private LocalBroadcastManager localManager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        localManager = LocalBroadcastManager.getInstance(this);

        //初始化接收器
        IntentFilter fliter = new IntentFilter();
        fliter.addAction(NOTINAME);
        LocalBroadReceiver receiver = new LocalBroadReceiver();
        localManager.registerReceiver(receiver, fliter);  //注册接收器


    }


    public void sendNotiMethod(View v) {

        Intent intent = new Intent(NOTINAME);
        localManager.sendBroadcast(intent); //发通知



    }

    /* 注册监听器 */
    class LocalBroadReceiver extends BroadcastReceiver {


        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "接受到本地广播", Toast.LENGTH_SHORT).show();
        }
    }

}
